package cn.tedu.wx.service.impl;

import cn.tedu.wx.constant.WxUrlConstant;
import cn.tedu.wx.service.IWxService;
import cn.tedu.wx.util.HttpClientUtil;
import cn.tedu.wx.util.SHA1;
import cn.tedu.wx.vo.AccessTokenBean;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Map;

@Service
public class WxServiceImpl implements IWxService {

    @Value("${wx.token}")
    private String token;

    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.appsecret}")
    private String appsecret;

    private AccessTokenBean accessTokenBean;

    @Override
    public String getAccessToken() {
        if (accessTokenBean == null || accessTokenBean.isExpired()) {
            synchronized (this) {
                if (accessTokenBean == null || accessTokenBean.isExpired()) {
                    refreshToken();
                }
            }
        }
        return accessTokenBean.getAccessToken();
    }

    private void refreshToken() {
        // 发送请求获取AccessToken
        String url = WxUrlConstant.ACCESS_TOKEN.replace("APPID",appId).replace("APPSECRET",appsecret);
        String s = HttpClientUtil.doGet(url);
        Map<String,Object> map = JSON.parseObject(s, Map.class);
        accessTokenBean = AccessTokenBean.responseOf(
                (String) map.get("access_token"),
                Long.parseLong(map.get("expires_in")+"")
        );
    }

    @Override
    public void checkWx(String signature, String timestamp, String nonce, String echostr) {
        // 排序
        String[] strings = new String[]{token,timestamp,nonce};
        Arrays.sort(strings);
        // 拼接
        StringBuilder builder = new StringBuilder();
        for (String string: strings) {
            builder.append(string);
        }
        String s = builder.toString();
        // 加密
        String selfSignature = SHA1.encode(s);
        // 比较
        if(!signature.equals(selfSignature)){
            throw new RuntimeException("校验失败");
        }
    }
}
